package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.ContractIn;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.entity.UnitOperator;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.Contract;
import com.wh.wisdomsite.xbox.st.service.IContractService;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 合同Controller
 *
 * @version V1.0
 * @Package: package com.wh.wisdomsite.xbox.server.controller.pr
 * @author: 蔡道行
 * @date: 2018-08-08 10:17
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/contract")
public class ContractController {

    private static final Log logger = LogFactory.getLog(ContractController.class);

    @Autowired
    private IContractService iContractService;

    @Autowired
    private IProjectService iProjectService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_contract_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/contract/contractList";
    }

    /**
     * 获取合同集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_contract_find")
    @RequestMapping(value = "/contractList.do")
    public void contractList(HttpServletResponse response, ContractIn in) {
        try {
            logger.info("加载合同数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<Contract> page = new Page<Contract>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Contract> ewContract = new EntityWrapper<Contract>();
            ewContract.setEntity(new Contract());
            //根据合同编号查询
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewContract.like("co.coNumber", in.getCoNumber());
            }
            //根据合同名称查询
            if (StringUtils.isNotEmpty(in.getCoName())) {
                ewContract.like("co.coName", in.getCoName());
            }
            //根据项目名称查询(根据项目ID)
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewContract.like("p.prName", in.getPrName());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewContract = UserUtils.setEntityWrapper(ewContract, "c1", "o1", "p");
            }
            ewContract.orderBy("createDate", false);
            Page<Map<String,Object>> contractPage = iContractService.getMapsPage(page,ewContract);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (contractPage.getRecords().size() > 0) {
                for (Map<String, Object> contract : contractPage.getRecords()) {
                    JSONObject object = new JSONObject(contract);
                    object.put("id", contract.get("coId"));
                    if(contract.get("project")!= null){
                        object.put("prName",((Project) contract.get("project")).getPrName());
                        object.put("prLeader",((Project)contract.get("project")).getPrLeader());
                        String date = "";
                        if(((Project)contract.get("project")).getPrRealStart() != null){
                            date = simpleDateFormat.format(((Project)contract.get("project")).getPrRealStart());
                        }
                        object.put("prRealStart", date);
                    }
                    if(contract.get("unitOperator")!=null){
                        object.put("uoMgr",((UnitOperator)contract.get("unitOperator")).getUoMgr());
                    }

                    array.put(object);
                }
            }
            json.put("total", contractPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载合同数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("加载合同数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 合同详情
     * @param contractIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_contract_view")
    @RequestMapping("/contractDesc.do")
    public String contractDesc( ContractIn contractIn, HttpServletRequest request) {
        try {
            logger.info("合同详情-->>开始");
            Map<String,Object> contract = iContractService.getMapById(contractIn.getCoId());
            if(contract.get("createBy") != null){
                contract.put("createBy", UserMapManager.getUserLoginNameInMap(contract.get("createBy").toString()));
            }
            if(contract.get("updateBy") != null){
                contract.put("updateBy", UserMapManager.getUserLoginNameInMap(contract.get("updateBy").toString()));
            }
            request.setAttribute("contract", contract);
            logger.info("合同详情-->>结束");
        }catch (Exception e){
            logger.debug("合同详情-->>Exception" + e.getMessage());
            e.printStackTrace();
        }
        return "/st/contract/contractDesc";
    }

    /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toContract.do")
    public ModelAndView toAddActivity(String coId, HttpServletRequest request) {
        logger.info("添加修改合同跳转-->>开始");
        Map<String,Object> contract = null;
        if(StringUtils.isNotEmpty(coId)){
            //contract
            contract = iContractService.getMapById(coId);
            request.setAttribute("contract", contract);
        }
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        request.setAttribute("companyId", companyId);
        logger.info("添加修改合同跳转-->>开始");
        return new ModelAndView("st/contract/contractOption");
    }

    /**
     * 更新或者修改
     * @param contract
     * @param response
     */
    @RequiresPermissions("rules:st_contract_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Contract contract, HttpServletResponse response) {
        try {
            logger.info("保存合同-->>开始");
            //判断方法是否已经存在,存在即更新.否则为添加
            String userId = UserUtils.getCurrentUser().getUsId();
            String compCode = UserUtils.getCurrentUser().getCompany().getCompCode();
            contract.setCompCode(compCode);
            iContractService.saveContract(userId,contract);
            response.getWriter().write(JsonUtil_Org.returnTrue("保存合同成功!"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("操作合同-->>Exception" + e.getMessage());
        }
    }

    /**
     * 删除合同
     *
     * @param
     * @param response
     */
    @RequiresPermissions("rules:st_contract_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String coId, HttpServletResponse response) {
        try {
            logger.info("删除合同-->>开始");
            iContractService.deleteById(coId);
            logger.info("删除合同-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("合同删除成功!"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除合同-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取项目合同集合作为combo使用
     * @param response
     */
    @RequestMapping(value = "/getContractListForCombo.do", method = RequestMethod.GET)
    public void getProjectListForCombo(HttpServletResponse response){
        try{
            logger.info("获取项目合同集合-->>开始");
            Page<Project> page = new Page<Project>();
            page.setCurrent(1);
            page.setSize(Integer.MAX_VALUE);
            EntityWrapper<Contract> ewContract = new EntityWrapper<Contract>();
            ewContract.setEntity(new Contract());
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewContract = UserUtils.setEntityWrapper(ewContract, "c1", "o1", "p");
            }
            ewContract.eq("co.dataState", 1);
            ewContract.orderBy("co.createDate", false);
            Page<Map<String,Object>> contractPage = iContractService.getMapsPage(page,ewContract);
            JSONArray jsonArray = new JSONArray();
            if(contractPage.getRecords().size() > 0){
                for(Map<String,Object> contract : contractPage.getRecords()){
                    JSONObject obj = new JSONObject();
                    obj.put("id",contract.get("coId"));
                    obj.put("text",contract.get("coName"));
                    jsonArray.put(obj);
                }
            }
            ResManager.getTextOut(response).print(jsonArray);
            logger.info("获取项目合同集合-->>结束");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 验证合同编号是否已经存在
     * @param coNumber
     * @param oldCoNumber
     * @return
     */
    @RequestMapping(value = "/coNumberIsExists.do", method = RequestMethod.POST)
    public void coNumberIsExists(HttpServletResponse response, String coNumber, String oldCoNumber){
        Map<String, Object> map = new HashMap<>();
        map.put("result", iContractService.coNumberIsExists(coNumber, oldCoNumber));
        JSONObject json = new JSONObject(map);
        ResManager.getTextOut(response).print(json);
    }


}
